<script setup lang="ts">
import {shopRoleOpts, shopTypes, statusOpts, supplierOpts} from "@/utils/status";
import {
  createSupplier,
  deleteSupplier,
  SupplierForm,
  supplierList,
  SupplierQuery,
  updateSupplier,
} from "@/api/supplier";

defineOptions({
  name: "Supplier",
  inheritAttrs: false,
});


const queryFormRef = ref(ElForm);
const objFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const current_role = localStorage.getItem("role_name");

const statusOptions = statusOpts();
const supplierOptions = supplierOpts();
const shopRoleOptins = shopRoleOpts();
const shopType = shopTypes();

const queryParams = reactive<SupplierQuery>({
  pageNum: 1,
  pageSize: 10,
});
const lists = ref<SupplierQuery[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const editVisible = ref(false);
const supplierId = ref();

const formData = reactive<SupplierForm>({
  status: 1,
});

const rules = reactive({
  title: [{required: true, message: "请输入名称", trigger: "blur"}],
  contact_name: [{required: true, message: "请输入联系人", trigger: "blur"}],
  status: [{required: true, message: "请选择状态", trigger: "blur"}],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  supplierList(queryParams)
    .then(({data}) => {
      lists.value = data.items || null;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}


/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 打开表单弹窗 */
function openDialog(id?: number) {
  editVisible.value = true;
  if (id) {
    supplierId.value = id;
  }
}

/** 保存提交 */
function handleSubmit() {
  objFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        updateSupplier(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        createSupplier(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            resetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭表单弹窗 */
function closeDialog(res: any = null) {
  console.log("closeDialog")
  editVisible.value = false;
  supplierId.value = undefined;
  // resetForm();
}

/** 重置表单 */
function resetForm() {
  objFormRef.value.resetFields();
  objFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除 */
function handleDelete(id: number) {
  if (!id) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteSupplier(id)
      .then(() => {
        ElMessage.success("删除成功");
        resetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form class="pull-left" ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="">
          <el-input v-model="queryParams.keywords" placeholder="店铺名称" clearable @keyup.enter="handleQuery"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search/>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <i-ep-refresh/>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <el-button v-hasPerm="['shop:supplier:add']" type="success" @click="openDialog()" class="pull-right">
        <i-ep-plus/>
        新增
      </el-button>
      <div class="clear"></div>
    </div>

    <el-card shadow="never" class="table-container">
      <el-table ref="dataTableRef" v-loading="loading" :data="lists" highlight-current-row>
        <el-table-column label="店铺ID" prop="id"/>
        <el-table-column label="店铺名称" prop="title"/>
        <el-table-column label="类型" prop="type">
          <template #default="scope">
            <el-tag :type="scope.row.type == 1 ?'success' : 'primary'">
              {{ shopType[scope.row.type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="所属园区" prop="park_title"/>
        <el-table-column label="所属商户" prop="supplier_title"/>
        <el-table-column label="负责人" prop="contact_name" min-width="100"/>
        <el-table-column label="联系方式" prop="contact_phone" min-width="100"/>
        <el-table-column label="访问权限" prop="roles">
          <template #default="scope">
            <el-tag :type="type%2== 1 ? 'success':'danger'" v-for="(type,tidx) in scope.row.roleIds" class="margin5-r">
              {{ shopRoleOptins[type] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="create_time"/>
        <el-table-column label="状态" align="center" width="160">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">
              {{ statusOptions[scope.row.status] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="店铺状态" align="center" width="160">
          <template #default="scope">
            <el-tag :type="scope.row.is_open == 1 ? 'success' : 'info'">
              {{ supplierOptions[scope.row.is_open] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template #default="scope">
            <el-link :href="'#/shop/stall?shop_id=' + scope.row.id" type="primary" class="margin5-b">管理档口</el-link>
            <el-button v-hasPerm="['shop:supplier:edit']" type="primary" class="margin5-b" link
                       @click="openDialog(scope.row.id)">
              <i-ep-edit class="margin3-r"/>
              编辑
            </el-button>
            <el-button v-hasPerm="['shop:supplier:delete']" type="danger" link @click="handleDelete(scope.row.id)"
                       style="margin-left: 0px;">
              <i-ep-delete class="margin3-r"/>
              删除
            </el-button>
          </template>

        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 编辑 -->
    <editSupplier :visible="editVisible" :supplierId="supplierId" @close="closeDialog"/>

  </div>
</template>

